<template>
  <el-drawer :title="form.id ? (detail ? $t('btn.Details') : $t('btn.edit')) : $t('operation.add')" v-model="visible" size="50%">
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="200px" :disabled="detail"
             v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('qms.specification')" prop="spec">
            <el-input v-model="form.spec" :placeholder="$t('qms.specification')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('qms.productionDate')" prop="manufactureDate">
            <el-date-picker value-format="YYYY-MM-DD" v-model="form.manufactureDate" :placeholder="$t('qms.productionDate')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('qms.sampleDeliveryTime')" prop="deliveryTime">
            <el-date-picker value-format="YYYY-MM-DD" v-model="form.deliveryTime" :placeholder="$t('qms.sampleDeliveryTime')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('qms.reportTime')" prop="reportTime">
            <el-date-picker value-format="YYYY-MM-DD" v-model="form.reportTime" :placeholder="$t('qms.reportTime')"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <sc-form-table
            v-model="form.qmsTiCheckDList"
            :placeholder="$t('table.noDataAvailable')"
        >
          <el-table-column align="center" :label="$t('qms.testItemCode')" prop="text">
            <template #default="{ row, $index }">
              <el-form-item label-width="0px" :prop="`qmsTiCheckDList.${$index}.checkProjectCode`"
                            :rules="[{ required: true, trigger: 'blur' }]">
                <el-input disabled v-model="row.checkProjectCode" style="width: 100%"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('qms.testItem')" prop="value">
            <template #default="{ row, $index }">
              <el-form-item label-width="auto" :prop="`qmsTiCheckDList.${$index}.checkProjectName`"
                            :rules="[{ required: true, trigger: 'blur' }]">
                <el-input disabled v-model="row.checkProjectName" style="width: 100%"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('qms.standardValue')" prop="selected">
            <template #default="{ row, $index }">
              <el-form-item label-width="auto" :prop="`qmsTiCheckDList.${$index}.standarditem`"
                            :rules="[{ required: false, trigger: 'blur' }]">
                <el-input disabled v-model="row.standarditem" style="width: 100%"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('qms.testData')" prop="testData">
            <template #default="{ row, $index }">
              <el-form-item label-width="auto" :prop="`qmsTiCheckDList.${$index}.testData`"
                            :rules="[{ required: false, trigger: 'blur' }]">
                <el-select :placeholder="$t('qms.testData')"
                           v-if="row.resultType === 'option'"
                           filterable
                           remote
                           v-model="row.testData">
                  <el-option v-for="item in selectList"
                             :key="item.text"
                             :label="item.text"
                             :value="item.text">
                    <span style="float: left">{{ item.text }}</span>
                  </el-option>
                </el-select>
                <el-input-number v-else v-model="row.testData" :label="$t('qms.testData')"/>

              </el-form-item>
            </template>
          </el-table-column>
        </sc-form-table>
      </el-row>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">{{$t('operation.Cancel')}}</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">{{$t('operation.confirm')}}</el-button>
        </span>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="BasDicSetDialog">
import {useMessage} from "/@/hooks/message";
import {getTI, qmsTiCheckHSave, qmsTiCheckHUpdate} from "/@/api/platform/qms/qmsRelationH";
import {getDetailBymasterId, getQmsTiCheckH} from "/@/api/platform/qms/qmsCheckReport";
import {useI18n} from "vue-i18n";

const {t} = useI18n();

const scFormTable = defineAsyncComponent(() => import('/@/components/FormTable/index.vue'));
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const detail = ref(false);
const selectList = ref([{"text": '合格\n' + 'Pass'}, {"text": '不合格\n' + 'Fail'}]);

const dataRules = {
  spec: [{required: true, trigger: 'blur'}],
  manufactureDate: [{required: true, trigger: 'blur'}],
  deliveryTime: [{required: true, trigger: 'blur'}],
  reportTime: [{required: true, trigger: 'blur'}],
}


// 定义字典

// 提交表单数据
const form = reactive({
  id: '',
  text: '',
  code: '',
  sort: '',
  remark: '',
  qmsTiCheckDList: [],
});


// 打开弹窗
const openDialog = (id: string, isDetail: boolean) => {
  visible.value = true
  detail.value = isDetail
  form.id = ''

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
    form.qmsTiCheckDList = [];
  });

  // 获取编辑信息
  if (id) {
    form.id = id
    getTiData(id)
  } else {
    getTI().then(res => {
      Object.assign(form.qmsTiCheckDList, res.data)
    });
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await qmsTiCheckHUpdate(form) : await qmsTiCheckHSave(form);
    useMessage().success(form.id ? t('qms.modifiedSuccessfully') : t('qms.addSuccessfully'));
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

// 初始化表单数据
const getTiData = async (id: string) => {
  // 等待第一个请求完成
  const qmsTiCheckHRes = await getQmsTiCheckH(id);

  Object.assign(form, qmsTiCheckHRes.data);

  // 等待第二个请求完成
  const detailRes = await getDetailBymasterId(id);
  detailRes.data.forEach(item =>{
    item.checkProjectCode = item.checkItemCode
    item.checkProjectName = item.checkItemName
  })
  form.qmsTiCheckDList = detailRes.data
};

// 暴露变量
defineExpose({
  openDialog
});
</script>